// pages/wallet/wallet.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 钱包余额
    balance: '1,288.50',
    balanceVisible: true,
    lastUpdateTime: '2024-10-15 15:30',
    
    // 交易流水（静态数据）
    transactions: [
      {
        id: 1,
        type: 'recharge',
        icon: '💰',
        title: '微信充值',
        desc: '钱包充值成功',
        amount: '200.00',
        time: '2024-10-15 14:30'
      },
      {
        id: 2,
        type: 'consume',
        icon: '🎮',
        title: '游戏陪玩',
        desc: '王者荣耀陪玩2小时',
        amount: '88.00',
        time: '2024-10-15 12:15'
      },
      {
        id: 3,
        type: 'recharge',
        icon: '💰',
        title: '支付宝充值',
        desc: '钱包充值成功',
        amount: '100.00',
        time: '2024-10-14 18:20'
      },
      {
        id: 4,
        type: 'consume',
        icon: '🛒',
        title: '商品购买',
        desc: '购买陪伴服务套餐',
        amount: '158.00',
        time: '2024-10-14 16:45'
      },
      {
        id: 5,
        type: 'withdraw',
        icon: '💳',
        title: '提现到银行卡',
        desc: '提现已到账',
        amount: '300.00',
        time: '2024-10-14 10:30'
      },
      {
        id: 6,
        type: 'consume',
        icon: '🎵',
        title: '语音陪聊',
        desc: '深夜陪聊1小时',
        amount: '45.00',
        time: '2024-10-13 23:15'
      },
      {
        id: 7,
        type: 'recharge',
        icon: '💰',
        title: '微信充值',
        desc: '钱包充值成功',
        amount: '500.00',
        time: '2024-10-13 20:00'
      },
      {
        id: 8,
        type: 'consume',
        icon: '🎬',
        title: '观影陪伴',
        desc: '一起看电影2小时',
        amount: '68.00',
        time: '2024-10-13 19:30'
      },
      {
        id: 9,
        type: 'consume',
        icon: '☕',
        title: '咖啡时光',
        desc: '下午茶陪伴聊天',
        amount: '38.00',
        time: '2024-10-13 15:20'
      },
      {
        id: 10,
        type: 'withdraw',
        icon: '💳',
        title: '提现到支付宝',
        desc: '提现处理中',
        amount: '200.00',
        time: '2024-10-12 14:10'
      },
      {
        id: 11,
        type: 'consume',
        icon: '🎯',
        title: '技能陪练',
        desc: '英语口语练习1小时',
        amount: '78.00',
        time: '2024-10-12 10:30'
      },
      {
        id: 12,
        type: 'recharge',
        icon: '💰',
        title: '银行卡充值',
        desc: '钱包充值成功',
        amount: '1000.00',
        time: '2024-10-11 16:45'
      },
      {
        id: 13,
        type: 'consume',
        icon: '🏃',
        title: '运动陪伴',
        desc: '晨跑陪伴30分钟',
        amount: '25.00',
        time: '2024-10-11 07:00'
      },
      {
        id: 14,
        type: 'consume',
        icon: '📚',
        title: '学习陪伴',
        desc: '读书分享会2小时',
        amount: '98.00',
        time: '2024-10-10 20:15'
      },
      {
        id: 15,
        type: 'consume',
        icon: '🍽️',
        title: '用餐陪伴',
        desc: '晚餐时光陪聊',
        amount: '35.00',
        time: '2024-10-10 18:30'
      }
    ],
    filteredTransactions: [],
    currentFilter: 'all',
    
    // 充值相关
    showRecharge: false,
    rechargeAmount: '',
    quickAmounts: [50, 100, 200, 500],
    selectedPayment: 'wechat'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.updateLastTime();
    this.initFilteredTransactions();
  },

  /**
   * 初始化筛选数据
   */
  initFilteredTransactions() {
    console.log('初始化交易数据，总数量:', this.data.transactions.length);
    this.setData({
      filteredTransactions: this.data.transactions,
      currentFilter: 'all'
    }, () => {
      console.log('筛选后数据数量:', this.data.filteredTransactions.length);
    });
  },

  /**
   * 更新最后更新时间
   */
  updateLastTime() {
    const now = new Date();
    const timeStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
    this.setData({
      lastUpdateTime: timeStr
    });
  },

  /**
   * 切换余额显示/隐藏
   */
  toggleBalanceVisible() {
    this.setData({
      balanceVisible: !this.data.balanceVisible
    });
  },

  /**
   * 筛选交易记录
   */
  filterTransactions(e) {
    console.log('filterTransactions 被调用', e);
    
    let filter = 'all';
    if (e && e.currentTarget && e.currentTarget.dataset && e.currentTarget.dataset.filter) {
      filter = e.currentTarget.dataset.filter;
    }
    
    console.log('筛选类型:', filter);
    console.log('原始数据数量:', this.data.transactions.length);
    
    let filtered = this.data.transactions;
    if (filter !== 'all') {
      filtered = this.data.transactions.filter(item => item.type === filter);
    }
    
    console.log('筛选后数据数量:', filtered.length);
    
    this.setData({
      currentFilter: filter,
      filteredTransactions: filtered
    }, () => {
      console.log('setData 完成，当前筛选:', this.data.currentFilter);
      console.log('当前显示数据数量:', this.data.filteredTransactions.length);
    });
  },

  /**
   * 查看全部交易
   */
  viewAllTransactions() {
    wx.navigateTo({
      url: '/pages/transactionHistory/transactionHistory'
    });
  },

  /**
   * 显示充值弹窗
   */
  showRechargeModal() {
    this.setData({
      showRecharge: true,
      rechargeAmount: ''
    });
  },

  /**
   * 隐藏充值弹窗
   */
  hideRechargeModal() {
    this.setData({
      showRecharge: false
    });
  },

  /**
   * 阻止事件冒泡
   */
  stopPropagation() {
    // 阻止点击弹窗内容时关闭弹窗
  },

  /**
   * 充值金额输入
   */
  onRechargeAmountChange(e) {
    this.setData({
      rechargeAmount: e.detail.value
    });
  },

  /**
   * 选择快捷金额
   */
  selectQuickAmount(e) {
    const amount = e.currentTarget.dataset.amount;
    this.setData({
      rechargeAmount: amount.toString()
    });
  },

  /**
   * 选择支付方式
   */
  selectPaymentMethod(e) {
    const method = e.currentTarget.dataset.method;
    this.setData({
      selectedPayment: method
    });
  },

  /**
   * 确认充值
   */
  confirmRecharge() {
    const amount = parseFloat(this.data.rechargeAmount);
    
    if (!amount || amount <= 0) {
      wx.showToast({
        title: '请输入有效的充值金额',
        icon: 'none'
      });
      return;
    }

    if (amount < 1) {
      wx.showToast({
        title: '充值金额不能低于1元',
        icon: 'none'
      });
      return;
    }

    if (amount > 10000) {
      wx.showToast({
        title: '单次充值金额不能超过10000元',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '发起支付...'
    });

    // 模拟支付流程
    setTimeout(() => {
      wx.hideLoading();
      
      // 调用微信支付
      this.requestPayment(amount);
    }, 1000);
  },

  /**
   * 发起微信支付
   */
  requestPayment(amount) {
    // 这里应该调用后端接口获取支付参数
    // 模拟支付成功
    wx.showToast({
      title: '充值成功',
      icon: 'success',
      duration: 2000,
      success: () => {
        // 更新余额
        const currentBalance = parseFloat(this.data.balance.replace(',', ''));
        const newBalance = (currentBalance + amount).toFixed(2);
        
        // 添加充值记录
        const newTransaction = {
          id: Date.now(),
          type: 'recharge',
          icon: '💰',
          title: '微信充值',
          desc: '钱包充值成功',
          amount: amount.toFixed(2),
          time: this.data.lastUpdateTime
        };

        const updatedTransactions = [newTransaction, ...this.data.transactions];
        
        this.setData({
          balance: this.formatBalance(newBalance),
          transactions: updatedTransactions,
          showRecharge: false,
          rechargeAmount: ''
        });
        
        this.filterTransactions();
        this.updateLastTime();
      }
    });
  },

  /**
   * 格式化余额显示
   */
  formatBalance(balance) {
    return parseFloat(balance).toLocaleString('zh-CN', {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2
    });
  },

  /**
   * 显示提现弹窗
   */
  showWithdrawModal() {
    wx.showToast({
      title: '提现功能开发中',
      icon: 'none'
    });
  },

  /**
   * 显示转账弹窗
   */
  showTransferModal() {
    wx.showToast({
      title: '转账功能开发中',
      icon: 'none'
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 页面显示时更新时间
    this.updateLastTime();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    // 模拟刷新数据
    wx.showToast({
      title: '刷新成功',
      icon: 'success'
    });
    
    this.updateLastTime();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    // 加载更多交易记录
    wx.showToast({
      title: '没有更多数据了',
      icon: 'none'
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '我的钱包',
      path: '/pages/wallet/wallet'
    };
  }
})